# 元组
# 创建元组
t1 = (1, 2, 3, 4, 5)
print(t1)   # (1, 2, 3, 4, 5)
t2 = tuple()
print(t2)   # ()
t3 = tuple([1, 2, 3, 4, 5])
print(t3)   # (1, 2, 3, 4, 5)

# 元组的基本操作
t4 = (1, 'hello', [1,2,3], True)
# 索引取值
print(t4[0])    # 1
print(t4[-1])   # True

# 切片操作
t5 = (1,2,3,4,5,6,7,8,9)
print(t5[2:5])  # (3, 4, 5)
print(t5[5:])   # (6, 7, 8, 9)
print(t5[:5])   # (1, 2, 3, 4, 5)
print(t5[::2])  # (1, 3, 5, 7, 9)
print(t5[::-1]) # (9, 8, 7, 6, 5, 4, 3, 2, 1)

# 查找元素索引
t6 = (1,2,3,4,5,6,7,8,5,9)
print(t6.index(5))  # 4
print(t6.index(5, 5))   # 8
print(t6.index(5, 3, 7))    # 4
try:
    print(t6.index(10))
except ValueError:
    print("没有找到元素")

# 统计元素在元组中出现次数
t7 = (1,2,3,4,5,6,7,8,5,9)
print(t7.count(5))  # 2
print(t7.count(10)) # 0

# 嵌套元组
t8 = (1,[1,2,3],{'name': '张三', 'age': 18}, True,(1,2))
print(t8[1][1]) # 2
print(t8[2]['name'])    # 张三


# 集合
# 创建集合
s1 = {1,2,3,4,5,3,2}
print(s1)   # {1, 2, 3, 4, 5}   它会自动去重
s2 = set()  # 空集合
print(s2)   # set()
s3 = set([1,2,3,2,4,5])
print(s3)   # {1, 2, 3, 4, 5}

# 向集合中添加元素
s2 = set()
s2.add(1)
s2.add(2)
s2.add(1)
print(s2)   # {1, 2}


# 删除元素
# pop()：随机删除一个元素，并返回被删除的元素，如果集合是空的会引发KeyError
s3 = {1,2,3,4,5}
print(s3.pop())

# remove()：删除集合中的元素，如果元素不存在会引发KeyError
s3.remove(2)
print(s3)
try:
    s3.remove(10)
except KeyError:
    print("元素不存在")

# discard(): 删除集合中的元素，如果元素不存在，则不会引发KeyError
s3.discard(3)
print(s3)
s3.discard(10)
print(s3)

# 集合运算
A = {1,2,3,4,5}
B = {4,5,6,7,8}
# 并集
print(A | B)    # {1, 2, 3, 4, 5, 6, 7, 8}
print(A.union(B))   # {1, 2, 3, 4, 5, 6, 7, 8}
# 交集
print(A & B)    # {4, 5}
print(A.intersection(B))    # {4, 5}
# 差集
print(A - B)    # {1, 2, 3}
print(A.difference(B))  # {1, 2, 3}
# 对称差集
print(A ^ B)    # {1, 2, 3, 6, 7, 8}
print(A.symmetric_difference(B))    # {1, 2, 3, 6, 7, 8}